package com.taldh;

import org.junit.Assert;
import org.junit.Test;

import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.BiFunction;

public class evalRPN {

    @Test
    public void evalRPNTest() {
        Assert.assertEquals(6, evalRPN(new String[]{"4", "13", "5", "/", "+"}));
    }

    private static ConcurrentMap<String, BiFunction> operator = new ConcurrentHashMap<>(4);

    static {
        operator.put("+", (a,b)-> (Integer)a + (Integer) b);
        operator.put("-", (a,b)-> (Integer)a - (Integer) b);
        operator.put("*", (a,b)-> (Integer)a * (Integer) b);
        operator.put("/", (a,b)-> (Integer)a / (Integer) b);
    }

    public int evalRPN(String[] tokens) {
        Stack<String> stack = new Stack<>();
        for (String token : tokens) {
            if (operator.containsKey(token)) {
                Integer a = Integer.valueOf(stack.pop());
                Integer b = Integer.valueOf(stack.pop());
                BiFunction biFunction = operator.get(token);
                Integer apply = (Integer) biFunction.apply(b, a);
                token = apply.toString();
            }
            stack.push(token);
        }
        return Integer.parseInt(stack.pop());
    }

}
